package 阻塞队列;

public class MyArrayBlockingQueue {
    //1.循环队列
    //2.线程安全
    //3.满了阻塞、空了 阻塞
    private int head=0;
    private int tail=0;
    //数组
    private int[]arr=new int[10];

    private boolean isFull(){
        if((head+1)%arr.length==tail){
            return true;
        }
        return false;
    }
    private boolean isNUll(){
        if(head==tail){
            return true;
        }
        return false;
    }

    //2.入队
    public void put(int tmp){
        synchronized (this){
            //1.判满
            while (isFull()){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            arr[head]=tmp;
            head=(head+1)% arr.length;
            //每一次成功入队，就尝试去唤醒空的时候的线程
            this.notify();
        }
    }

    //3.出队
    public int take(){
        synchronized (this){
           while (isNUll()){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
           int tailOld=arr[tail];
            tail=(tail+1)%arr.length;
            //每一次成功出队，尝试去唤醒满时阻塞的线程
            this.notify();
            return tailOld;
        }
    }
}
